package com.ouheng.common.utils;

import java.util.List;
import java.util.Map;
import java.util.concurrent.CountDownLatch;

import org.apache.log4j.Logger;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.ouheng.wxgz.WxGzpush;

public class WxPushThreadImpl  implements Runnable{
	
		private String access_token;//公众号token
	    private Map<String,Object> parameter;
	    private List<String> openIdList;//微信OpenID列表
	    private String content;//消息内容
	    private int currentIndex;//当前索引
	    private int rows;//处理数据条数
	    private CountDownLatch doneSignal;//处理线程条数

	    public WxPushThreadImpl(String access_token,List<String> openIdList, String content, int currentIndex, int rows, CountDownLatch doneSignal,Map<String,Object> parameter) {
	        this.openIdList = openIdList;
	        this.content = content;
	        this.currentIndex = currentIndex;
	        this.rows = rows;
	        this.doneSignal = doneSignal;
	        this.parameter=parameter;
	        this.access_token=access_token;
	    }

	
	    private static Logger logger = Logger.getLogger(WxPushThreadImpl.class);
	
	    @Override
	    public void run() {
	        // 查询当前的block范围内的发送的OpenID---------
	        JSONArray openIdArray = filterOpenIds(openIdList, currentIndex, rows);
	        try {
	        	for (int i = 0; i < openIdArray.size(); i++) {
	        		WxGzpush.send(openIdArray.getString(i),parameter);
				}
	          // DSHWechatAPIHander.sendMessage(accessToken, msgJson.toString());
	        } catch (Exception e) {
	            logger.error("send message thread exception=>{" + openIdArray.toString() + "}{" + e.getMessage() + "}");
	            e.printStackTrace();
	        } finally {
	            doneSignal.countDown();//工人完成工作，计数器减一
	        }
	    }
	    
	    
	    
	    
	    private JSONArray filterOpenIds(List<String> openIdList, int currentIndex, int rows) {
	        int startIndex = currentIndex * rows;
	        int endIndex = (currentIndex + 1) * rows;
	        if (endIndex > openIdList.size()) {
	            endIndex = openIdList.size();
	        }
	        JSONArray openIdArray = new JSONArray();
	        for (int i = startIndex; i < endIndex; i++) {
	            openIdArray.add(openIdList.get(i));
	        }
	        return openIdArray;
	    }
	    
}
